package com.aop.aop;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.aop.domain.TestInterface;
import com.aop.event.InterfaceEvent;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @Description:
 * @author: zxl
 * @Data:2021/3/24
 */
@Aspect
@Component
@Slf4j
public class ControllerInterceptor4 {

    @Resource
    private HttpServletRequest request;

    @Resource
    private ApplicationEventPublisher applicationEventPublisher;

    // 定义切点Pointcut
    @Pointcut(value = "execution(public * com.aop.controller..*.*(..)))")
    public void executeService() {
    }

    @Around("executeService()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        String requestURI = request.getRequestURI();
        Object result = null;
        long start = System.currentTimeMillis();
        try {
            result = joinPoint.proceed();
            log.info("当前request路径 ：  ", requestURI);
            log.info("URL ： " + request.getRequestURL());
            log.info("HTTP_METHOD ：  " + request.getMethod());
            log.info("IP ：  " + request.getRemoteAddr());
            log.info("CLASS_METHOD ：  " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            log.info("ARGS ： " + Arrays.toString(joinPoint.getArgs()));

        } catch (Throwable t) {
            log.error(t.getMessage(), t);
        } finally {
            String className = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
            String methodName = joinPoint.getSignature().getName();
            String method = request.getMethod();
            String url = request.getRequestURI();
            long endTime = System.currentTimeMillis() - start;
            TestInterface testInterface = TestInterface.builder().interfaceClassName(className).interfaceMethod(method).interfaceMethodName(methodName).interfaceUrl(url).costTime(endTime).build();
            // 执行结束后，获取 url 进行判断，如果为 bigInterfaceList 所需要统计的路径，则推送记录调用事件
            // 获取访问路径: 项目名+servlet);
            //去数据库查询查询当前接口是否已经被记录,
            applicationEventPublisher.publishEvent((new InterfaceEvent(testInterface)));
        }
        return result;

    }
}
